const express = require('express');
const { hash } = require('utility');
const db = require('../db');
const router = express.Router();

//-------------------------------------------获取用户信息接口-------------------------------
router.get('/userinfo', (req,res) => {
    // console.log(req.user);  //这里用到id值  id是要在token中保存的数据 而token 中保存的数据 赋值给req.user
    // console.log(req);
    // return;
    db('select * from user where id='+ req.user.id,(err,result) => {
        if(err) throw err;
        res.send({
            status:0,
            message:'获取用户信息成功',
            data:result[0],
        });

    });
});

//-------------------------------------------更新用户信息接口-------------------------------

/*
请求方式：POST,
请求接口：/my/user/userinfo
Content-Type:application/x-www-form-urlencoded
请求体： email | nickname | id
*/
router.post('/userinfo',(req,res) => {
    let {id,nickname,email } = req.body;
    if (id != req.user.id) {
        return res.send({status:1,message:'无权更新'});
    }
    let sql = `update user set nickname='${nickname}',email='${email}' where id=${id}`; 
    db(sql,(err,result) => {
        if(err) throw err;
        res.send({status:0,message:'更新用户信息成功'});
    });
});

//-------------------------------------------更新头像接口-------------------------------
router.post('/avatar',(req,res) => {
    // console.log(req.body);  // { avatar: '' }
    let sql = `update user set user_pic='${req.body.avatar}' where id=${req.user.id}`;
    db(sql, (err,result) => {
        if(err) throw err;
        res.send({status: 0 , message:'更换头像成功'});
    });
});

//-------------------------------------------重置密码接口-------------------------------

// router.post('/updatepwd', (req,res) => {
//     // console.log(req.body);  //{ oldPwd: 'admin', newPwd: 'admin123' }
//     let {oldPwd,newPwd} = req.body;
//     if (oldPwd === newPwd) {
//         res.send({status:1,message:'新密码和旧密码不能相同'});
//     }
//     let sql = `update user set oldPwd=${oldPwd},newPwd=${newPwd} where id=${req.user.id}`;
//     db(sql,(err,result) => {
//         if(err) throw err;
//         res.send({status:0,message:'更新密码成功'});
//     });
// });



module.exports = router;